use std::process::{Command, Stdio};
use std::io::{BufRead, BufReader};
use std::sync::mpsc::{channel, Sender, Receiver};
use std::thread;
use std::sync::{Arc, Mutex};

pub struct Console {
    output_buffer: Vec<String>,
    receiver:  Arc<Mutex<Receiver<String>>>,
    sender: Arc<Mutex<Sender<String>>>,
}

impl Clone for Console {
    fn clone(&self) -> Self {
        Console {
            sender: self.sender.clone(),
            receiver: self.receiver.clone(),
            output_buffer: self.output_buffer.clone(),
        }
    }
}

impl Console {
    pub fn new() -> Self {
        let (sender, receiver) = channel();
        Self {
            output_buffer: Vec::new(),
            receiver: Arc::new(Mutex::new(receiver)),
            sender: Arc::new(Mutex::new(sender)),
        }
    }

    pub fn execute_command(&mut self, program: &str, args: &[&str], stop_flag: Arc<Mutex<bool>>) {
        let program = program.to_string(); // 转换为拥有所有权的 String
        let args: Vec<String> = args.iter().map(|&s| s.to_string()).collect(); // 转换为拥有所有权的 Vec<String>
        let sender = self.sender.clone();
        
        thread::spawn(move || {
            let process = Command::new(program)
                .args(&args)
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .spawn();
    
            match process {
                Ok(mut child) => {
                    let stdout = child.stdout.take().unwrap();
                    let stderr = child.stderr.take().unwrap();
                    
                    let stdout_reader = BufReader::new(stdout);
                    let stderr_reader = BufReader::new(stderr);
    
                    // 处理标准输出
                    for line in stdout_reader.lines() {
                        if *stop_flag.lock().unwrap() {
                            let _ = sender.lock().unwrap().send("任务已停止".to_string());
                            let _ = child.kill();
                            break;
                        }
                        if let Ok(line) = line {
                            let _ = sender.lock().unwrap().send(line);
                        }
                    }
    
                    // 处理标准错误
                    for line in stderr_reader.lines() {
                        if *stop_flag.lock().unwrap() {
                            let _ = sender.lock().unwrap().send("任务已停止".to_string());
                            let _ = child.kill();
                            break;
                        }
                        if let Ok(line) = line {
                            let _ = sender.lock().unwrap().send(format!("错误: {}", line));
                        }
                    }
                }
                Err(e) => {
                    let _ = sender.lock().unwrap().send(format!("执行命令失败: {}", e));
                }
            }
        });
    }

    pub fn update(&mut self) {
        while let Ok(line) = self.receiver.lock().unwrap().try_recv() {
            self.output_buffer.push(line);
        }
    }

    pub fn get_output(&self) -> &Vec<String> {
        &self.output_buffer
    }

    pub fn append_output(&mut self, message: String) {
        self.output_buffer.push(message);
    }
}